<html>
<head>

<title>Groovy Goodness: Executing String or List</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Executing String or List</h3>

<div class="post">
<p>Groovy adds the <code>execute()</code> method to the <code>String</code> and <code>List</code> classes. When we invoke the <code>execute()</code> we get a <code>Process</code> object back. We can get information from this object with some Groovy added methods. For example to get the output of the command we only have to access the <code>text</code> property. Or we can access the input and output streams to send data to the process or retrieve data from the <a href="http://groovy.codehaus.org/Process+Management">process</a>.</p>
<pre class="brush:groovy">
new File('.').eachFileMatch(~/.*.jpg$/) {
    // Use ImageMagick convert command to create a thumbnail for a JPEG image.
    def converter = "convert ${it.name} -thumbnail 100x100 thumb-${it.name - '.jpg'}.gif".execute()
    converter.waitFor()
    
    if (converter.exitValue()) {
        println "Error creating thumbnail for ${it.name}:"
        println converter.text
    } else {
        println "Created a thumbnail for ${it.name}."
    }
}

// We can also use a List. Useful if arguments have spaces or 
// for shell wildcards like *.
def thumbnail = ["convert", "file.jpg", "-thumbnail", "100x100", "thumb-file.gif"].execute()
thumbnail.waitFor()

println "Exit value: ${thumbnail.exitValue()}"
println "Output: ${thumbnail.text}"
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>